package com.service;

import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.ESBaseData;
/**
 * index相关的service
 * @author shaoyuxia
 *
 * @param <T>
 */
public abstract class AbstractIndexService<T extends ESBaseData> implements IService<T> {

	private static final Logger logger = LoggerFactory.getLogger(AbstractIndexService.class);
	@Autowired
	protected ObjectMapper mapper;

	@Autowired
	protected TransportClient client;

	/**
	 * 创建index,已经存在则默认成功
	 * 
	 * @param index
	 * @param type
	 * @param mappingJson
	 * @return false:失败，true成功
	 */
	public boolean addIndex(String index, String type, String mappingJson) {
		if (index != null) {
			index = index.toLowerCase();
			if (!isIndexExist(index)) {
				logger.debug("index:" + index + ",type:" + type + ",mapping:" + mappingJson);
				CreateIndexRequestBuilder cirb = client.admin().indices().prepareCreate(index);
				cirb.addMapping(type, mappingJson, XContentType.JSON);
				CreateIndexResponse resp = cirb.execute().actionGet();
				return resp.isAcknowledged();
			} else {
				logger.warn("index is already existed:" + index);
			}
		}
		return false;

	}

	/**
	 * 删除index
	 * 
	 * @param index
	 * @return
	 */
	public boolean deleteIndex(String index) {
		IndicesAdminClient admin = client.admin().indices();
		DeleteIndexResponse resp = admin.prepareDelete(index).execute().actionGet();
		return resp.isAcknowledged();
	}

	/**
	 * 判断index是否存在
	 * 
	 * @param index
	 * @return
	 */
	public boolean isIndexExist(String index) {
		try {
			return client.admin().indices().exists(new IndicesExistsRequest(index)).get().isExists();
		} catch (InterruptedException | ExecutionException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

}
